数据结构与算法——二叉树(2)

求二叉树中两个结点的最大公共父节点

​ 1

​ /
​ 2 3
​ / \ /
4 5 6 7
/\ /\ /\ /\

如上图所示,由正整数 1, 2, 3, ...组成了一棵无限大的二叉树。从某一个结点到根结点(编号是1的结点)都有一条唯一的路径,比如从5到根结点的路径是(5, 2, 1),从4到根结点的路径是(4, 2, 1),从根结点1到根结点的路径上只包含一个结点1,因此路径就是(1)。对于两个结点x和y,假设他们到根结点的路径分别是(x1, x2, ... ,1)和(y1, y2,...,1),那么必然存在两个正整数i和j,使得从xi 和yj 开始,有xi = yj,xi + 1 = yj + 1,xi + 2 = yj + 2,...
现在的问题就是,给定x和y,要求他们的公共父节点,即xi(也就是 yj)。

示例

输入

10 4  //输入包含多组数据,每组数据包含两个正整数x和y(1≤x, y≤2^31-1)。

输出

2  //对应每一组数据,输出一个正整数xi,即它们的首个公共父节点。

Java

import java.util.Scanner;

public class Main{

    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        while(scanner.hasNext()) {
            int x=scanner.nextInt();
            int y=scanner.nextInt();

            while(x!=y) {
                if(x>y)
                    x=x/2;
                else
                    y=y/2;
            }
            System.out.println(x);
        }
    }
}
// https://blog.csdn.net/zd454909951/article/details/78855707

C++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){
//    freopen("a.txt", "r", stdin);
    int x, y;
    while(cin >> x >> y){
        //选出二者中间最大的数,设为y
        while(x != y){
            if(x > y){
                x /= 2;
            }
            else{
                y /= 2;
            }
        }
        cout << x << endl;
    }
    return 0;
}
//https://blog.csdn.net/Void_worker/article/details/81123175

二叉树的序列化

二叉树被记录成文件的过程叫做二叉树的序列化。序列化的方法有很多,这里我们采用括号序列的方法将其序列化,所谓括号序列指的是对于一个节点生成一个括号,括号内是其子树的括号序列,其中左儿子(若存在)的括号在前,右儿子(若存在)的括号在后。对于给定的树,请设计高效的算法,将其序列化。

给定一个树的根节点指针root,请返回一个字符串,代表其序列化后的括号序列。

C++

//https://www.nowcoder.com/questionTerminal/e3a3a1a956914d8ca5688ea47a5cf9c9

import java.util.*;
 
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}*/
public class TreeToSequence {
    public String toSequence(TreeNode root) {
        // write code here
        String str="";ui,,0/'[-;;;0]'
            return "";
        }else{
            str="(";
            str+=toSequence(root.left);
            str+=toSequence(root.right);
            str+=")";
            return str;
        }
    }
}

Java

//https://www.nowcoder.com/questionTerminal/e3a3a1a956914d8ca5688ea47a5cf9c9

class TreeToSequence {
public:
    string getAns(TreeNode *root){
        string temp;
        if(!root) return temp;
        string s1,s2;
        if(root->left)
           s1 = getAns(root->left);
        if(root->right)
           s2 =getAns(root->right);
        temp+='(';
        temp+=s1;
        temp+=s2;
        temp+=')';
        return temp;
         
    }
    string toSequence(TreeNode* root) {
         string ans;
         if(!root) return ans;
         ans=getAns(root);
         return ans;
    }
};

给出一棵二叉树,返回这棵树的中序遍历

例如:

给出的二叉树为{1,#,2,3},

   1↵    ↵     2↵    /↵   3↵

返回[1,3,2].

备注:递归的解法太没有新意了,你能用迭代的方法来解这道题吗?

如果你不清楚“{1,#,2,3}"的含义的话,请继续阅读

我们用如下方法将二叉树序列化:

二叉树的序列化遵循层序遍历的原则,”#“代表该位置是一条路径的终结,下面不再存在结点。

例如:

   1↵  / ↵ 2   3↵    /↵   4↵    ↵     5

上述的二叉树序列化的结果是:"{1,2,3,#,#,4,#,#,5}".

Java

//https://www.nowcoder.com/questionTerminal/1b25a41f25f241228abd7eb9b768ab9b

/*
* 非递归实现二叉树的中序遍历
*/
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        ArrayList<Integer> res = new ArrayList<Integer>();
        TreeNode node = root;
        while (!stack.isEmpty() || node != null) {
            while (node != null) {
                stack.push(node);
                node = node.left;
            }
            node = stack.pop();
            res.add(node.val);
            node = node.right;
        }
        return res;
    }

C++

//https://www.nowcoder.com/questionTerminal/1b25a41f25f241228abd7eb9b768ab9b

class Solution {
public:
    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> result;
        if(!root)
            return result;
        stack<TreeNode*> s;
        TreeNode *p=root;
        while(!s.empty() || p!=NULL)
        {
            while(p)
            {
                s.push(p);
                p=p->left;  
            }
            if(!s.empty())
            {
                p = s.top();
                s.pop();
                result.push_back(p->val);
                p = p->right;
            }
        }
        return result;
    }
};
posted @ 2020-01-17 13:05  小萝卜鸭  阅读(285)  评论(0编辑  收藏  举报