[snap] find next neighbor on binary tree

给一个binary tree,每一个node含有parent指向parent,给定一个node,找出他右侧的node。

instant

用了dfs,顺着左,右,父的顺序找,标记了高度。

package snapchat;


import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class FindNeighborNode {



    public TreeNode findNeighbor(TreeNode self){
        TreeNode p = self.parent;
        if(p == null)return null;

        Set visited = new HashSet<>();

        visited.add(self);
        return findLeftMost(self,0,0,visited);




    }

    public TreeNode findLeftMost(TreeNode cur, int curHeight,int targetHeight,Set visited){
        if(!visited.contains(cur) && curHeight == targetHeight)return cur;

        visited.add(cur);

        if(cur.left != null && !visited.contains(cur.left)){
            TreeNode l = findLeftMost(cur.left,curHeight - 1, targetHeight,visited);
            if(l != null)return l;
        }
        if(cur.right != null && !visited.contains(cur.right)){
            TreeNode r = findLeftMost(cur.right,curHeight - 1,targetHeight,visited);
            if(r != null)return r;

        }
        if(cur.parent != null && !visited.contains(cur.parent)){
            TreeNode p = findLeftMost(cur.parent,curHeight + 1,targetHeight,visited);
            if(p != null)return p;
        }

        return null;



    }

    public static void main(String[] args){
        FindNeighborNode fnn = new FindNeighborNode();
        TreeNode root = new TreeNode(10);
        TreeNode t5 = root.left = new TreeNode(5);
        root.left.parent = root;
        TreeNode t15 = root.right = new TreeNode(15);
        root.right.parent = root;
        TreeNode t3 = root.left.left = new TreeNode(3);

        TreeNode t1 = root.left.left.left = new TreeNode(1);
        TreeNode t12 = root.right.left = new TreeNode(12);
        TreeNode t14 = root.right.left.right = new TreeNode(14);

        t3.parent = t5;
        t1.parent = t3;
        t12.parent = t15;
        t14.parent = t12;

        TreeNode res = fnn.findNeighbor(t1);
        System.out.println(res.val);
    }

}

你可能感兴趣的:([snap] find next neighbor on binary tree)